package com.naiterui.ehp.bs.patient.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.naiterui.ehp.bp.support.context.ResourceHolder;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.security.HeaderConstant;
import com.naiterui.ehp.bp.support.security.PatientLoginInterceptor;
import com.naiterui.ehp.bp.support.security.SettingConfig;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bp.utils.context.SpringContextHolder;
import com.naiterui.ehp.bs.patient.exception.ExceptionCodes;
import com.naiterui.ehp.bs.patient.rpc.IWeixinRemoter;
import com.naiterui.ehp.bs.patient.service.security.ISecurityService;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor extends PatientLoginInterceptor {


    @Override
    protected boolean verifyToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*String patientId = request.getParameter(SettingConfig.PATIENT_ID);
        String token = request.getParameter(SettingConfig.TOKEN);

        ISecurityService securityService = SpringContextHolder.getBean(ISecurityService.class);
        return securityService.saveCheckToken(patientId, token, response);*/

        boolean result = false;

        String origin = request.getHeader(HeaderConstant.HEADER_ORIGIN);

        String doctorId = request.getParameter(SettingConfig.DOCTOR_ID);
        String patientId = request.getParameter(SettingConfig.PATIENT_ID);

        if (StringUtils.isNumeric(origin)) {
            Long id = null;
            String token = null;
            switch (Integer.parseInt(origin)) {
                case HeaderConstant.HEADER_ORIGIN_PATIENT_APP:
                    // 如果是医生pc端和小程序端的token 是通过header头传递的
                    token = request.getHeader(SettingConfig.TOKEN_HEADER);
                    // String token = request.getHeader(tokenHeader);
                    log.info("患者拦截器获取到的token信息 :{}", token);
                    id = this.checkMiniToken(token);
                    log.info("校验token获取登录用户ID为 {}", id);
                    if (id != null) {
                        log.info("资源持有器线程上下文-存入数据-AP，patientId {}", id);
                        ResourceHolder.bindResource(SettingConfig.PATIENT_ID, id);
                        result = true;
                    }
                    break;
                case HeaderConstant.HEADER_ORIGIN_PATIENT_WX:
                    patientId = request.getParameter(SettingConfig.PATIENT_ID);
                    token = request.getParameter(SettingConfig.TOKEN);
                    log.info("患者拦截器获取到的token信息 :{}", token);
                    ISecurityService securityService = SpringContextHolder.getBean(ISecurityService.class);
                    result = securityService.saveCheckToken(patientId, token, response);
                    break;
                default:
                    result = false;
                    break;
            }
        }
        if (!result) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));// 支持跨域请求
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");// 是否支持cookie跨域
            response.setHeader("Access-Control-Allow-Headers", "*");// Origin, X-Requested-With, Content-Type,
                                                                    // Accept,Access-Token
            response.setHeader("Access-Control-Max-Age", "3600");
            response.getWriter().println(JsonMapper.toJson(PublicService.returnResponseVO(ExceptionCodes.TOLOGIN)));
        }

        return result;
    }

    private Long checkMiniToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        IWeixinRemoter remoter = SpringContextHolder.getBean(IWeixinRemoter.class);
        try {
            Long id = remoter.checkMiniToken(token);
            log.info("checkMiniToken id:{}", id);
            return id;
        } catch (BusinessException e) {
            log.error("校验小程序token失败", e);
        }
        return null;
    }
}